﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Rankep.FilterableDataGridView;
using DiveManager.Benutzerverwaltung;

namespace DiveManager
{
    public partial class ManageUsersForm : Form
    {
        protected DiveDatabaseEntities diveDatabase;
        protected BindingSource bindingSourceTabBenutzer;
        protected BindingSource bindingSourceTabRechte;
        protected BindingSource bindingSourceTabRechteGroups;

        // Item Filter
        private FilterItem textboxFilter;

        public ManageUsersForm()
        {
            InitializeComponent();

            // Init Database
            diveDatabase = new DiveDatabaseEntities();
        }

        private void ManageUsersForm_Load(object sender, EventArgs e)
        {
            bindingSourceTabBenutzer = new BindingSource();
            bindingSourceTabRechte = new BindingSource();
            bindingSourceTabRechteGroups = new BindingSource();

            loadUserTabBenutzer();

            // Add Bindings
            tbUsername.DataBindings.Add(new Binding("Text", bindingSourceTabBenutzer, "Name"));

            // Add Filtering
            textboxFilter = new FilterItem("", "Name");
        }

        private void loadUserTabBenutzer()
        {            
            IQueryable<User> dataQuery = (from a in diveDatabase.User
                                          orderby a.Name ascending
                                          select a);

            // Bind Data to BindingSource
            bindingSourceTabBenutzer.DataSource = dataQuery;
            // Bind BindingSource to List
            dgUser.DataSource = bindingSourceTabBenutzer;

            dgUser.Columns["ID"].Visible = false;
            dgUser.Columns["Password"].Visible = false;
            dgUser.Columns["initialpassword"].Visible = false;

        }

        //private void loadUserTabRechte()
        //{
        //    IQueryable<User> dataQueryUser = (from a in diveDatabase.User
        //                                      orderby a.Name ascending
        //                                      select a);

        //    // Bind Data to BindingSource
        //    bindingSourceTabRechte.DataSource = dataQueryUser;
        //    // Bind BindingSource to List
        //    lboxUser.DataSource = bindingSourceTabRechte;

        //    lboxUser.DisplayMember = "Name";
        //    lboxUser.ValueMember = "ID";
        //}

        private void tsbUserDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Den Benutzer wirklich löschen?", "Rückfrage", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                if ((bindingSourceTabBenutzer.Current as User).Name == "DiveStar")
                {
                    MessageBox.Show("Der Benutzer DiveStar darf nicht gelöscht werden!", "Fehler", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (bindingSourceTabBenutzer.Current != null)
                {
                    User currentUser = bindingSourceTabBenutzer.Current as User;
                    diveDatabase.DeleteObject(currentUser);
                    diveDatabase.SaveChanges();
                    loadUserTabBenutzer();
                }
            }
        }

        private void tsbUserAdd_Click(object sender, EventArgs e)
        {
            // Generate new Object for DB
            User newUser = new User();
            newUser.ID = Guid.NewGuid();
            newUser.Name = "<neuer Eintrag>";
            newUser.Password = new Security().GetMD5Hash("12345");
            newUser.initialpassword = true;

            // Add to DB
            int anzahl = (from a in diveDatabase.User
                          where a.Name == "<neuer Eintrag>"
                          select a).Count();
            if (anzahl > 0)
            {
                MessageBox.Show("Der Benutzer <neuer Eintrag> existiert schon!", "Fehler", MessageBoxButtons.OK, MessageBoxIcon.Error);                
            }
            else
            {
                dgUser.EndEdit();
                diveDatabase.AddToUser(newUser);
                diveDatabase.SaveChanges();
                loadUserTabBenutzer();
                foreach (DataGridViewRow row in dgUser.Rows)
                {
                    row.Selected = false;
                    
                    if ((string)row.Cells["Name"].Value == "<neuer Eintrag>")
                    {                        
                        row.Selected = true;
                        bindingSourceTabBenutzer.Position = row.Index;
                        tbUsername.Enabled = true;
                    }
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            diveDatabase.SaveChanges();
        }

        //private void loadSecurityGroups()
        //{
        //    IQueryable<SecurityGroups> sg = (from g in diveDatabase.SecurityGroups
        //                                     select g);
        //    // Bind Data to BindingSource
        //    bindingSourceTabRechteGroups.DataSource = sg;
        //    // Bind BindingSource to List
        //    lboxGruppen.DataSource = bindingSourceTabRechteGroups;

        //    lboxGruppen.DisplayMember = "Name";
        //    lboxGruppen.ValueMember = "ID";
        //}

        private void dgUser_SelectionChanged(object sender, EventArgs e)
        {
            if (dgUser.CurrentRow == null) { return; }

            if ((string)dgUser.CurrentRow.Cells["Name"].Value == "DiveStar")
            {
                tbUsername.Enabled = false;
            }
            else
            {
                tbUsername.Enabled = true;
            }
        }

        private void btnZuruecksetzen_Click(object sender, EventArgs e)
        {
            PasswordResetForm passreset = new PasswordResetForm();
            if (passreset.ShowDialog() == System.Windows.Forms.DialogResult.OK && passreset.NewPass != null)
            {
                Guid usrID = (Guid)dgUser.CurrentRow.Cells["ID"].Value;
                if (usrID != null)
                {
                    User usr = (from a in diveDatabase.User
                                where a.ID == usrID
                                select a).First();
                    usr.Password = new Security().GetMD5Hash(passreset.NewPass);
                    usr.initialpassword = true;
                    diveDatabase.SaveChanges();
                    MessageBox.Show("Passwort wurde geändert!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        //private void tcManageUser_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    switch (tcManageUser.SelectedTab.Text)
        //    {
        //        case "Rechtevergabe":
        //            loadUserTabRechte();
        //            loadSecurityGroups();
        //            break;
        //       case "Benutzer":
        //            loadUserTabBenutzer();
        //            break;
        //    }
        //}

        //private void lboxUser_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        lboxGruppen.SelectedIndex = 0;
        //        clbRights.SelectedIndex = 0;
        //    }
        //    catch (ArgumentOutOfRangeException)
        //    {
                
        //    }
        //}

        //private void lboxGruppen_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    var relations = (from rel in diveDatabase.RelationSecuritygroupsSecurityrights
        //                                                                    join sr in diveDatabase.SecurityRights on rel.rightID equals sr.ID 
        //                                                                    into relWithName

        //                                                                  where rel.groupID == (Guid)lboxGruppen.SelectedValue 
        //                                                                  select relWithName);
        //}
    }
}
